<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Warehouse_transfer extends CI_Controller {

	public function index()
	{
	   $this->load->model('Warehouse_transfer_model');
           $this->load->model('warehouses_xproducts_model');
           $this->load->helper(array('form', 'url'));            
	   $document_code = null;
	   $id_warehouse_o = null;
           $id_warehouse_d = null;
	   $date = null;
           $observations =null;
            
	    if ($this->input->post('document_code')) {
	        $document_code = $this->input->post('document_code');
	    }
	    if ($this->input->post('id_warehouse_o')) {
	        $id_warehouse_o = $this->input->post('id_warehouse_o');
	    }
            if ($this->input->post('id_warehouse_d')) {
	        $id_warehouse_d = $this->input->post('id_warehouse_d');
	    }
	    if ($this->input->post('date')) {
	        $date = $this->input->post('date');
	    }
            if ($this->input->post('observations')) {
	        $observations = $this->input->post('observations');
	    }
            $warehouses = $this->warehouses_xproducts_model->getAll();
	    /*if ($code != null || $id_warehouse != null || $desde != null || $hasta != null) {
	        $kardex = $this->Kardex_model->search($code, $id_warehouse, $desde, $hasta);
	    }*/
            
            $vars['document_code'] = $document_code;
            $vars['warehouses'] = $warehouses;
            $vars['id_warehouse_o'] = $id_warehouse_o;
            $vars['id_warehouse_d'] = $id_warehouse_d;
            $vars['content_view'] = 'warehouse_transfer';   
	    $vars['menu'] = 'warehouses';
            $vars['date'] = $date;
            $vars['observations'] = $observations; 
                        
	    $this->load->view('template', $vars);
	}
        
        public function codetransfer() {
        $this->load->model('Document_types_model');
        $codetransfer = $this->Document_types_model->generanum_transfer();

        foreach ($codetransfer as $c) {
            $codestring = $c->document_code;
            $num = (int) $codestring + 1;
            echo str_pad((int) $num, 12, "0", STR_PAD_LEFT);
        }
        }
        
        public function search_code_unique() {
        $this->load->model('Warehouse_transfer_model');
        $document_code = $this->input->post('code_transfer');
        echo $this->Warehouse_transfer_model->comparaction_code($document_code);
        }
        
        public function reporte() {
            
           $this->load->model('Kardex_model');
           $this->load->model('warehouses_xproducts_model');
           $this->load->model('Sales_model');
           $this->load->model('Warehouses_model');
           $this->load->model('Products_model');
           
           $this->load->helper(array('form', 'url'));            
	   $code = null;
	   $id_warehouse = null;
	   $desde = null;
           $hasta =null;
           
           
	    if ($this->input->post('code')) {
	        $code = $this->input->post('code');
	    }
	    if ($this->input->post('warehouses')) {
	        $id_warehouse = $this->input->post('warehouses');
	    }
	    if ($this->input->post('desde')) {
	        $desde = $this->input->post('desde');
                $datei = $this->input->post('desde');
                $date = str_replace('/', '-', $datei);
                $datedesde = date("Y-m-d", strtotime($date) );
	    }
            if ($this->input->post('hasta')) {
	        $hasta = $this->input->post('hasta');
                $datei = $this->input->post('hasta');
                $date = str_replace('/', '-', $datei);
                $datehasta = date("Y-m-d", strtotime($date) );
	    }
            
            $product = $this->Products_model->find($code);
            $namewarehouse = $this->Warehouses_model->find($id_warehouse);
            $warehouses = $this->warehouses_xproducts_model->getAll();
	    if ($code != null || $id_warehouse != null || $desde != null || $hasta != null) {
	        $kardex = $this->Kardex_model->search($code, $id_warehouse, $datedesde, $datehasta);
	    }
            $listar_stock_product_almacen = $this->Sales_model->select_almacen_productos($code,$id_warehouse);
             foreach ($listar_stock_product_almacen as $lis ){
            $scajas = $lis->boxes;
            $spaquetes = $lis->packs;
            $sunidades = $lis->Units;
             }
            $vars['scajas'] = $scajas;
            $vars['spaquetes'] = $spaquetes;
            $vars['sunidades'] = $sunidades;
            $vars['code'] = $code;
            $vars['warehouses'] = $warehouses;
            $vars['id_warehouse'] = $id_warehouse;
            $vars['content_view'] = 'kardex_search';   
	    $vars['menu'] = 'warehouses';
            $vars['desde'] = $desde;
            $vars['hasta'] = $hasta; 
            $vars['kardex'] = $kardex;
            $vars['namewarehouse'] = $namewarehouse;
            $vars['product'] = $product;
            $this->load->view('kardex_by_product', $vars);
             
	    //$this->load->view('template', $vars);
    }



        public function add($success_message = null) {
        $this->load->model('Document_types_model');
        $this->load->model('warehouses_model');
        $vars['typeDocuments'] = $this->Document_types_model->select_guide_sale();
        $vars['warehouses'] = $this->warehouses_model->getAll();
        if (isset($success_message)) {
            $vars['success_message'] = true;
        }
       
          $vars['content_view'] = 'warehouse_transfer';        
          $vars['menu'] = 'warehouses';
         $this->load->view('template', $vars);
      }

    public function adda($success_message = null) {
        $this->load->model('Document_types_model');
        $this->load->model('warehouses_model');
        $vars['typeDocuments'] = $this->Document_types_model->select_guide_sale();
        $vars['warehouses'] = $this->warehouses_model->getAll();
        if (isset($success_message)) {
            $vars['success_message'] = true;
        }
       
          $vars['content_view'] = 'warehouse_transfer';        
          $vars['menu'] = 'warehouses';
         $this->load->view('template', $vars);
      }
    
    
    public function products($success_message = null) {
        $code = null;
        $description = null;
        $id_warehouse_o = null;
        $this->load->model('Products_model');
        $this->load->model('warehouses_model'); 
        if ($this->input->post('code')) {
            $code = $this->input->post('code');
        }
        if ($this->input->post('description')) {
            $description = $this->input->post('description');
        }
        if ($this->input->post('id_warehouse_o')) {
            $id_warehouse_o = $this->input->post('id_warehouse_o');
        }         
        $products = array();
        if (isset($success_message)) {
	            $vars['success_message'] = true;
	}
        if ($code != null || $description != null) {
            $products = $this->Products_model->search($code, $description);            
        }

        if (isset($success_message)) {
            $vars['success_message'] = true;
        }
        $warehouse_o = $this->warehouses_model->find($id_warehouse_o);
        $vars['products'] = $products;
        $vars['code'] = $code;        
        $vars['description'] = $description;
        $vars['warehouse_o'] = $warehouse_o;
        $this->load->view('products_list_transfer', $vars);
    }
   

    
    
     public function stocks() {
        $code = null;
        $description = null;
        $id_warehouse_o = null;
        if ($this->input->post('code')) {
            $code = $this->input->post('code');
        }
        if ($this->input->post('description')) {
            $description = $this->input->post('description');
        }
        if ($this->input->post('id_warehouse_o')) {
            $id_warehouse_o = $this->input->post('id_warehouse_o');
        }  
        $this->load->model('Warehouses_product_model');
        $this->load->model('Products_model');
        $listStock = $this->Warehouses_product_model->listStockByProductAndWarehouse($code,$id_warehouse_o);
        $productData = $this->Products_model->find($code);
        $vars['priceProduct'] = $productData->price;
        $vars['codeProduct'] = $code;
        $vars['descriptionProduct'] = $description;
        $vars['listStock'] = $listStock;        
        $vars['productData'] = $productData;
        $vars['id_warehouse_o'] = $id_warehouse_o;
        $this->load->view('stock_list_transfer', $vars);
    }



    public function submit() {

        $this->load->model('warehouse_transfer_model');
        $this->load->model('Sales_model');
        $this->load->model('Shop_model');
        $this->load->model('Warehouses_product_model');
        $typedocument = 5;
        $code_transfer = $this->input->post('code_transfer');
        $datei = $this->input->post('date');
        $date = str_replace('/', '-', $datei);
        $datef = date("Y-m-d", strtotime($date) );           
        $observations = $this->input->post('observations');
        if ($observations == '') 
            {
            $observations = ' ';
            }
        $id_warehouse_o = $this->input->post('id_warehouse_o');
        $id_warehouse_d = $this->input->post('id_warehouse_d');

                $data = array('document_type_id' => $typedocument,
                    'document_code' => $code_transfer,
                    'date' => $datef,                    
                    'observations' => $observations);                  
                $vars['success'] = $this->warehouse_transfer_model->add_transfer($data);               
                $contenaumentador = $this->input->post('contenaumentador');

                for ($i = 1; $i <= $contenaumentador; $i++) {

                    $product_code = $this->input->post('code_product_'.$i);
                    $box = $this->input->post('total_cajas_'.$i);
                    $pack = $this->input->post('total_paquetes_'.$i);
                    $unit = $this->input->post('total_unidades_'.$i);
                   /*  echo "<script language='JavaScript'>alert('Code.$product_code');</script>";
                      echo "<script language='JavaScript'>alert('box.$box');</script>";
                       echo "<script language='JavaScript'>alert('pack.$pack');</script>";
                       echo "<script language='JavaScript'>alert('unit.$unit');</script>";
                       echo "<script language='JavaScript'>alert('id_o.$id_warehouse_o');</script>";
                       echo "<script language='JavaScript'>alert('id_d.$id_warehouse_d');</script>";*/
                       
                    $data = array('document_code' => $code_transfer,
                        'product_code' => $product_code,
                        'box' => $box,
                        'pack' => $pack,
                        'unit' => $unit,
                        'id_warehouse_o' => $id_warehouse_o,
                        'id_warehouse_d' => $id_warehouse_d);
                        
                    if( $product_code == 0 ){ 
                        /*si el campo codigo del producto no tiene ningun codigo entonces no grabara en la guia (esto es por que como ai un incrementador que va sumando +1 por cada producto que se va ingresando a la guia detalle, el aumentador sera usado 
                            en el nombre de cada campo 1 que pertence a tal fila y por ello si borramos algun producto el aumentador no dismiuira porque las demas filas necesitan el valor del aumentador actual y el nombre de la fila no cambiara, solo seguir el aumento que ha llevado hasta el momento) 
                          ejemplo: si llevamos 4 productos por el momento.. en el detalle de guia seria fila 1, fila 2, fila 3, fila 4, pero si decidimos borrar el primero quedaria fila2, fila3 , fila4, pero el aumentador es hasta 4 osea cuando corra el for correra hasta 4
                          aunque el primero fila1 no exita.. osea hay uno de sobra.. y como sobra, pero tiene un campo codigo_1_fila_1 resgitrado ese campo estara en 0 y el sistema no deberia gaurdarlo por que ocupa espacio
                        */

                    }else{
                        $this->warehouse_transfer_model->add_details_transfer($data); 
                    }
                   
       
                          $listar_stock_product_almacen_o = $this->Sales_model->select_almacen_productos($product_code,$id_warehouse_o);// busca las cajas paquetes y unidades del producto "n" hubicado en el alamacen "n"
                          $listar_stock_product_almacen_d = $this->Sales_model->select_almacen_productos($product_code,$id_warehouse_d);
                          $productos_en_alamcenes = $this->Shop_model->select_almacen_productos($product_code,$id_warehouse_d);
                            foreach ($listar_stock_product_almacen_o as $lis ){
                         //cajas, paquetes y unidades actuales en el almacen de los productos
                           $cajas = $lis->boxes;
                           $paquetes = $lis->packs;
                           $unidades = $lis->Units;
                           
                         //recorrido de todos los inpust  generados y enviados desde el detalle de guia de venta
                           $pide_caja = $this->input->post('total_cajas_'.$i); //recorrido del input caja del almacen "n" de la fila "n" (fila se refiere el posicion horizontal en que estan hubicadas en el detalle de guia de venta)
                           $cajas_actual = $cajas - $pide_caja; //realiza la operacion de restar las cajas actuales en el almacen con las cajas pedidas y los coloca en una variable
                          
                           $pide_paquete = $this->input->post('total_paquetes_'.$i);//''
                           $paquete_actual = $paquetes - $pide_paquete;//''
                         
                           $pide_unidad = $this->input->post('total_unidades_'.$i);//''
                           $unidades_actual = $unidades - $pide_unidad;//''
                           
                            $this->Sales_model->edit_stock_warehouse_product($product_code,$id_warehouse_o,$cajas_actual,$paquete_actual,$unidades_actual);
                        }
                        foreach ($listar_stock_product_almacen_d as $lis ){
                         //cajas, paquetes y unidades actuales en el almacen de los productos
                           
                           
                         //recorrido de todos los inpust  generados y enviados desde el detalle de guia de venta
                           
                           $pide_caja = $this->input->post('total_cajas_'.$i); //recorrido del input caja del almacen "n" de la fila "n" (fila se refiere el posicion horizontal en que estan hubicadas en el detalle de guia de venta)
                           //$cajas_actual = $cajas + $pide_caja; //realiza la operacion de restar las cajas actuales en el almacen con las cajas pedidas y los coloca en una variable
                          
                           $pide_paquete = $this->input->post('total_paquetes_'.$i);//''
                           //$paquete_actual = $paquetes + $pide_paquete;//''
                         
                           $pide_unidad = $this->input->post('total_unidades_'.$i);//''
                          // $unidades_actual = $unidades + $pide_unidad;//''
                           
                           if(count($productos_en_alamcenes)<=0)
                            {                   
                              $res = $this->Warehouses_product_model->add($product_code,$id_warehouse_d,$pide_caja,$pide_paquete,$pide_unidad,0);                   
                             // echo "<script language='JavaScript'>alert('Inserto.$res');</script>";  
                            }
                            else
                            {
                              $res = $this->Warehouses_product_model->add($product_code,$id_warehouse_d,$pide_caja,$pide_paquete,$pide_unidad,1);                   
                            //  echo "<script language='JavaScript'>alert('Actualizo.$res');</script>";                        
                            } 
                        }
             
          
                    
          
                }

          
                //echo "<script language='JavaScript'>alert('Exito de Traslado de Almacen');</script>";
               $this->add(true) && adda(true) ;
    }
}